package Tcp;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class TcpClient {

    private Socket socket;

    public TcpClient(String clientIp, int port){
        try {
            socket = new Socket(clientIp, port);

//            System.out.println(socket.getLocalAddress());
//            System.out.println(socket.getPort());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

    public void start() {
        //这时socket和服务器已经建立了连接
        //建立lo流
        System.out.println("建立");
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()) {

            //用来读取控制台的输入
            Scanner scanner = new Scanner(System.in);

            //套壳 方便操作
            Scanner scannerToNet = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream);

            while(true) {

                //获取请求  空格传不过去
                String request = scanner.nextLine();
                System.out.println("request = " + request);

                //将请求输出到流中
                writer.println(request);

                //刷新缓冲区
                writer.flush();

                //读取回复
                System.out.println("等待回复");
                System.out.println(scannerToNet.nextLine());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public static void main(String[] args) {
        TcpClient client = new TcpClient("127.0.0.1", 9990);
        client.start();
//        Scanner in = new Scanner(System.in);
//        Pattern pattern = Pattern.compile("\n");
//        while (in.hasNext()) {
//            System.out.println(in.nextLine());
//        }

    }
}
